package com.zsc.shixun.service.function.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.shixun.contant.Contant;
import com.zsc.shixun.entity.Article;
import com.zsc.shixun.entity.User;
import com.zsc.shixun.model.home.HomeVO;
import com.zsc.shixun.model.home.UserArticleVO;
import com.zsc.shixun.service.IArticleService;
import com.zsc.shixun.service.IUserService;
import com.zsc.shixun.service.function.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 首页
 * </p>
 *
 * @author ZWYZY
 * @since 2020/6/17
 */
@Service
@Transactional
public class HomeServiceImpl implements HomeService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public HomeVO getData(Long id) {
        if (redisTemplate.hasKey(Contant.HOME_KEY + id)) {
            return (HomeVO) redisTemplate.opsForValue().get(Contant.HOME_KEY + id);
        }
        HomeVO homeVO = new HomeVO();
        List<UserArticleVO> userArticleVOArrayList = new ArrayList<>(10);
        LambdaQueryWrapper<Article> queryWrapper = new QueryWrapper<Article>().lambda().eq(Article::getUserId, id);
        homeVO.setClickNumber(articleService.list(queryWrapper).stream().mapToLong(Article::getClickNumber).sum());
        User user = userService.getById(id);
        List<Article> articleList = articleService.list(queryWrapper.orderByDesc(Article::getCreateTime).last("limit 5"));
        articleList.forEach(a -> {
            UserArticleVO userArticleVO = new UserArticleVO();
            userArticleVO.setClickNumber(a.getClickNumber());
            userArticleVO.setCommentNumber(a.getCommentNumber());
            userArticleVO.setImg(user.getImg());
            userArticleVO.setUsername(user.getUsername());
            userArticleVO.setLikeNumber(a.getLikeNumber());
            userArticleVO.setTitle(a.getTitle());
            userArticleVOArrayList.add(userArticleVO);
        });

        homeVO.setHomeVOList(userArticleVOArrayList);
        redisTemplate.opsForValue().set(Contant.HOME_KEY + id, homeVO);
        return homeVO;
    }
}
